package com.guigu.basedservice.controller;

import com.alibaba.excel.EasyExcel;
import com.guigu.basedservice.entity.BasePartsType;
import com.guigu.basedservice.listener.PageReadListener;
import com.guigu.basedservice.mapper.BasePartsTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author heyuhang
 * @create 2024/9/27
 */
@CrossOrigin
@RestController
@RequestMapping("/api/excel")
public class ExcelController {

    @Autowired(required = false)
    private BasePartsTypeMapper basePartsTypeMapper;

    // 写入 Excel
//    @PostMapping("/write")
//    public String writeExcel() {
//        String fileName = "D:\\S4项目小组\\备份\\GraduationProject\\service\\service-based\\src\\main\\resources\\goodsexcel1.xlsx";
//        EasyExcel.write(fileName, BasePartsType.class)
//                .sheet("模板")
//                .doWrite(data());
//        return "写入成功";
//    }

    @PostMapping("/write")
    public String writeExcel(@RequestParam String filePath) {
        // Use the passed file path
        EasyExcel.write(filePath, BasePartsType.class)
                .sheet("模板")
                .doWrite(data());
        return "写入成功, 文件路径: " + filePath;
    }

    // 读取 Excel
    @PostMapping("/read")
    public String readExcel() {
        String fileName = "D:\\S4项目小组\\备份\\GraduationProject\\service\\service-based\\src\\main\\resources\\goodsexcel2.xlsx";
        PageReadListener pageReadListener = new PageReadListener();
        EasyExcel.read(fileName, BasePartsType.class, pageReadListener).sheet().doRead();
        List<BasePartsType> list = pageReadListener.getList();
        int result = basePartsTypeMapper.addManyBasePartsType(list);
        return "读取成功，插入记录数: " + result;
    }

    private List<BasePartsType> data() {
        return basePartsTypeMapper.queryAll();
    }
}
